package com.memoryangelapplication.services;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;

import com.memoryangelapplication.AlertMessageActivity;
import com.memoryangelapplication.global.Event_pass;
import com.memoryangelapplication.model.EventObj;

import android.app.AlarmManager;
import android.app.PendingIntent;
import android.content.BroadcastReceiver;
import android.content.ContentValues;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.util.Log;
import android.widget.Toast;

public class PendingEventAlarm extends BroadcastReceiver {

	private SQLiteDatabase mydb;
	private static final String DATABASE_NAME = "memoryangel.db";
	private String MEM_EVENT = "table_events";

	private Context passcontext;
	private int alarmType;

	ArrayList<EventObj> lst = new ArrayList<EventObj>();

	private final String REMINDER_BUNDLE = "MyReminderBundle";

	public PendingEventAlarm() {
	}

	public PendingEventAlarm(Context context, Bundle extras,
			int timeoutInSeconds) {

		passcontext = context;

		AlarmManager alarmMgr = (AlarmManager) context
				.getSystemService(Context.ALARM_SERVICE);
		Intent intent = new Intent(context, PendingEventAlarm.class);
		intent.putExtra(REMINDER_BUNDLE, extras);
		PendingIntent pendingIntent = PendingIntent.getBroadcast(context, 0,
				intent, PendingIntent.FLAG_UPDATE_CURRENT);

		Calendar time = Calendar.getInstance();
		time.setTimeInMillis(System.currentTimeMillis());
		time.add(Calendar.SECOND, timeoutInSeconds);

		/*
		 * alarmMgr.set(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(),
		 * pendingIntent);
		 */

		/*
		 * alarmMgr.setInexactRepeating(AlarmManager.RTC_WAKEUP,
		 * time.getTimeInMillis(), 1000*60, pendingIntent);
		 */

		alarmMgr.setRepeating(AlarmManager.RTC_WAKEUP, time.getTimeInMillis(),
				1000 * 45, pendingIntent);

		/*
		 * alarmMgr.setRepeating(AlarmManager.ELAPSED_REALTIME,
		 * time.getTimeInMillis(), 1000 * 60, pendingIntent);
		 */
	}

	@Override
	public void onReceive(Context context, Intent intent) {

	

		String dateString = getCurrentTimeString().toString();
		String dateStringTime = getCurrentTimeStringTime().toString();

	/*	dateString = dateString.replaceAll("-", "").trim();
		dateStringTime = dateStringTime.replaceAll(":", "").trim();
		String StrdateString = dateString.trim() + dateStringTime;*/
		dateString = dateString.replaceAll("-", "");
	
		String[] CheckAMPM = dateStringTime.split(" ");
		String CheckHourMin = CheckAMPM[0];
		String CheckAMPMSTR = CheckAMPM[1];
		
		String[] CheckHourMinArr = CheckHourMin.split(":");
		String CheckHour = CheckHourMinArr[0];
		String CheckMin = CheckHourMinArr[1];
		
		
		if(CheckAMPMSTR.equals("PM")){
			int CheckHourVal = Integer.parseInt(CheckHour);
			int CheckH = CheckHourVal + 12;
			CheckHour = Integer.toString(CheckH);
		}
		else if(CheckAMPMSTR.equals("AM") && CheckHour.equals("12")){
			CheckHour = "00";
		}
		
		String StrdateString = dateString.trim() + ""+ CheckHour + ""+ CheckMin;
		Log.d("IN Activity", "XXXXXX :"+StrdateString);

	/*	Toast.makeText(context, "Alarm went off in equal"+StrdateString, Toast.LENGTH_SHORT)
		.show();*/
		mydb = context.openOrCreateDatabase(DATABASE_NAME,
				Context.MODE_PRIVATE, null);
		ContentValues newrowfDealer = new ContentValues();
		Cursor fdealerrows = null;

		try {

			fdealerrows = mydb.query(MEM_EVENT, null, "event_alam_time = '"
					+ StrdateString + "' AND event_active = '0'", null, null,
					null, null);
			

		} catch (Exception e) {
		}

		if (fdealerrows != null) {
			/*Toast.makeText(context, "Equal not null", Toast.LENGTH_SHORT)
					.show();*/
			if (fdealerrows.getCount() > 0) {

				fdealerrows.moveToFirst();
				while (fdealerrows.isAfterLast() == false) {
					lst.add(new EventObj(fdealerrows.getString(3), fdealerrows
							.getString(4), fdealerrows.getString(2),
							fdealerrows.getString(7), fdealerrows.getString(4),
							fdealerrows.getString(5), fdealerrows.getString(6),
							fdealerrows.getString(7), fdealerrows.getString(9),
							fdealerrows.getString(8), fdealerrows.getString(6),
							fdealerrows.getString(16), fdealerrows
									.getString(17), fdealerrows.getString(18), fdealerrows.getString(1)));
					fdealerrows.moveToNext();
				}

			} else {

			}
		}
		mydb.close();

		// /Pass Data To Global class Event_pass
		// Event_pass.setData_pass(lst);

		if (!lst.isEmpty()) {
			EventObj mth = (EventObj) lst.get(0);
			Event_pass.setData_pass(lst);

			if (mth != null) {
				Intent i2 = new Intent(context, AlertMessageActivity.class);
				i2.putExtra("event_log_id", mth.getEvent_event_log_id());
				i2.putExtra("event_id", mth.getEvent_time_stamp());
				i2.putExtra("event_title", mth.getEvent_title());
				i2.putExtra("event_date", mth.getEvent_date());
				i2.putExtra("event_time", mth.getEvent_time());
				i2.putExtra("event_description", mth.getEvent_description());
				i2.putExtra("event_eventremindertime", mth.getEvent_eventremindertime());
				i2.putExtra("event_eventremindernumber", mth.getEvent_eventremindernumber());
				i2.putExtra("event_eventwaittime", mth.getEvent_eventwaittime());
				i2.putExtra("nxt_incr", "1");
				i2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				context.startActivity(i2);
			}
		}

	}

	private void runOnUiThread(Runnable runnable) {
		// TODO Auto-generated method stub

	}

	private String getCurrentTimeString() {
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("yyyy-MM-dd");
		String date_to_string = ddMMMyyFormat.format(c.getTime());
		return date_to_string;
	}

	private String getCurrentTimeStringTime() {
		Date dateNow = new Date();
		Calendar c = Calendar.getInstance();
		SimpleDateFormat ddMMMyyFormat = new SimpleDateFormat("hh:mm a");
		String date_to_string = ddMMMyyFormat.format(c.getTime());
		return date_to_string;
	}

	public class AlertUI extends AsyncTask<String, Void, String> {

		private Context asynccontext;

		public AlertUI(Context passContext) {

			super();
			asynccontext = passContext;

		}

		@Override
		protected String doInBackground(String... urls) {

			for (int i = 0; i < lst.size(); i++) {
				EventObj mth = (EventObj) lst.get(i);

				Intent i2 = new Intent(asynccontext, AlertMessageActivity.class);
				i2.putExtra("event_title", mth.getEvent_title());
				i2.putExtra("event_date", mth.getEvent_date());
				i2.putExtra("event_time", mth.getEvent_time());
				i2.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
				asynccontext.startActivity(i2);

			}

			// asynccontext.startActivity(i1);

			return null;
		}

	}

}
